for _ in range(5):
print("Are we there yet?")
NOTES
_, __, ___, etc.for _ in range() loop to repeat the same thing over and overis_green = True
for _ in range(10):
if is_green:
print("green!")
else:
print("red!")
is_green = not is_green
NOTES
is_green = not is_greenis_green from False to True. Run it again.for i in range(10): if i % 2 == 0...while loop and no variable keeping track of the iteration countThere are two players. Each takes a turn choosing an integer. The game ends when the sum of all numbers exceeds 100. The person with the highest individual sum wins.
easy_game.py¶def get_response(prompt):
response = int(input(prompt))
def play_easy_game():
is_first = True
total = 0
sum_a = 0
sum_b = 0
while total < 100:
if is_first:
response = get_response('Player 1: ')
total += response
sum_a += response
else:
response = get_response('Player 2: ')
total += response
sum_b += response
is_first = not is_first
if sum_a > sum_b:
print('Player 1 wins!')
else:
print('Player 2 wins!')
play_easy_game()
abs¶abs(7-9)
abs(9-7)
while and continue¶def get_number():
while True:
response = int(input('Enter a number less than 10: '))
if response > 10:
print('That was not less than 10. :P')
continue
return response
get_number()
NOTES
continue with a while loopnumber_game.py¶The inputs to the program are the lower bound, upper bound, and number of players.
The computer randomly picks a number between the lower bound and upper bound.
Each player is prompted to guess a number.
A guess is invalid if:
If a player submits an invalid guess, they should be informed why their guess was invalid and they must guess again.
The player that is closest wins. Ties go to the player that guessed earlier.
NOTES
while True + continue + return designimport random
def is_integer(text):
if not text:
return False
for c in text:
if not c.isdigit():
return False
return True
def prompt_integer(prompt, lower, upper, invalid):
while True:
response = input(prompt)
if not is_integer(response):
print("Please enter a positive integer.")
continue
response = int(response)
if response < lower or response > upper:
print(f"The number must be between {lower} and {upper}.")
continue
if response in invalid:
print("That number has already been guessed. Guess another.")
continue
return response
def find_winner(number, responses):
winner_index = 0
for index in range(1, len(responses)):
if abs(responses[index]-number) < abs(responses[winner_index]-number):
winner_index = index
return winner_index
def play_number_game(lower, upper, num_players):
number = random.randint(lower, upper)
responses = []
for player in range(num_players):
response = prompt_integer(f'Player {player + 1} guess: ', lower, upper, responses)
responses.append(response)
print(f"The number is {number}")
winner = find_winner(number, responses)
print(f'Player {winner + 1} wins!')
# if __name__ == '__main__':
# play_number_game(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
play_number_game(1, 100, 5)
abswhile and continue